package com.feinno.urcs.group.service;

import com.feinno.cpim.CpimMessage;
import com.feinno.database.DataRow;
import com.feinno.database.DataTable;
import com.feinno.database.Database;
import com.feinno.urcs.group.GroupConfiguration;
import com.feinno.urcs.group.api.GroupMessageStorageService;
import com.feinno.urcs.group.entity.GroupTextMessageStorageEntity;
import com.feinno.urcs.group.util.CpimUtils;
import com.feinno.urcs.group.util.MSRPTextMsgParser;
import com.feinno.urcs.group.util.MsrpContent;
import com.feinno.urcs.profile.entity.ClientType;
import com.feinno.urcs.sip.UrcsSipFactory;
import com.feinno.urcs.types.MobileNo;
import com.feinno.util.DateUtil;
import com.google.gson.Gson;
import org.helium.framework.annotations.FieldSetter;
import org.helium.framework.annotations.ServiceImplementation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sip.address.SipURI;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 用于群消息的存储
 *
 * @author Li.Hongbo <lihongbo@feinno.com>
 */
@ServiceImplementation
public class GroupMessageStorageServiceImpl implements GroupMessageStorageService {

	private static final Logger LOGGER = LoggerFactory.getLogger(GroupMessageStorageServiceImpl.class);

	@FieldSetter("${RMSDB}")
	private Database rmsdb;

	@Override
	public long storageTextMessage(int groupId, MobileNo sender, String contentType, byte[] content, ClientType clientType) throws Exception {
		try {
			if (clientType == ClientType.PC) {
				MsrpContent textContent = new MsrpContent(content);
				LOGGER.info("GroupSessionMessageTask.processTask, send text....");
				String message = MSRPTextMsgParser.getMsrpMsgContent(textContent);
				Matcher m = Pattern.compile("<Font.*?>([\\s\\S]*?)</Font>").matcher(message);
				while (m.find()) {
					message = m.group(1).trim();
				}
				SipURI groupUri = UrcsSipFactory.getAddressFactory().createSipURI(GroupConfiguration.INSTANCE.getGroupPrefix() + groupId, GroupConfiguration.INSTANCE.getGroupDomain());
				CpimMessage cpim = CpimUtils.createCpim(message.getBytes(), sender, groupUri, textContent.getContentType(), true, DateUtil.getUTCNow());
				content = cpim.getByteArray();
			}
			GroupTextMessageStorageEntity entity = new GroupTextMessageStorageEntity();
			entity.setGroupId(groupId);
			entity.setSender(sender);
			entity.setMessageBarcycle(false);
			entity.setMessageContentType(contentType);
			entity.setTextContent(content);
			entity.setTextContentType(contentType);
			entity.setTextDateTime(new Date());
			entity.setMessageClientType(clientType);
			return storageTextMessage(entity);
		} catch (Exception e) {
			LOGGER.error("create group error : {}", e);
			throw e;
		}
	}

	@Override
	public boolean hasGroupMessage(int groupId, long startOffset) throws Exception {
		String sql = "select group_message_id from  group_message_text where groupId=? and  group_message_id>=? limit 1";

		DataTable dt = rmsdb.executeTable(sql, groupId, startOffset);
		if (dt.getRows() != null && dt.getRows().size() > 0) {
			return true;
		}
		return false;
	}

	public Collection<GroupTextMessageStorageEntity> getTextMessage(int groupId, long groupMessageStorageId, int maxSize) {

		String sql = "select * from  group_message_text where groupId=? and  group_message_id>= ? order by group_message_id  limit ?";
		List<GroupTextMessageStorageEntity> result = new ArrayList<>();
		DataTable dt = null;
		try {
			dt = rmsdb.executeTable(sql, groupId, groupMessageStorageId, maxSize);
			if (dt.getRows() != null) {
				for (DataRow dr : dt.getRows()) {
					// Groupmember赋值
					GroupTextMessageStorageEntity entity = new GroupTextMessageStorageEntity(dr);
					result.add(entity);
				}
			}
		} catch (SQLException e) {
			LOGGER.error(String.format("getGroupTextMessage Error groupId=%s,groupMessageStorageId=%s,maxSize=%s", groupId, groupMessageStorageId, maxSize), e);
		}
		return result;

	}

	public long storageTextMessage(GroupTextMessageStorageEntity storageEntity) throws Exception {
		Object[] args = null;
		try {
			String sql = "insert into group_message_text(" +
					"groupId," +
					"sender," +
					"message_barcycle," +
					"message_content_type," +
					"text_content," +
					"text_content_type," +
					"text_content_disposition," +
					"text_content_transfer_encoding," +
					"text_imdn_message_id," +
					"text_imdn_disposition_notification," +
					"text_dateTime," +
					"client_type " +

					") values(?,?,?,?,?,?,?,?,?,?,?,?);";

			args = new Object[]{
					storageEntity.getGroupId(),
					storageEntity.getSender().toString(),
					storageEntity.getMessageBarcycle(),
					storageEntity.getMessageContentType(),
					storageEntity.getTextContent(),
					storageEntity.getTextContentType(),
					storageEntity.getTextContentDisposition(),
					storageEntity.getTextContentTransferEncoding(),
					storageEntity.getTextImdnMessageId(),
					storageEntity.getTextImdnDispositionNotification(),
					storageEntity.getTextDateTime(),
					storageEntity.getMessageClientType().intValue()
			};
			return rmsdb.executeInsertWithAutoColumn(sql, args);
		} catch (Exception e) {
			LOGGER.error("storageTextMessage error args =" + new Gson().toJson(args), e);
			throw e;
		}
	}
}
